package aliyun.cx.admin.service.impl;

import aliyun.cx.admin.entity.Role;
import aliyun.cx.admin.entity.RolePermission;
import aliyun.cx.admin.entity.UserRole;
import aliyun.cx.admin.mapper.RoleMapper;
import aliyun.cx.admin.mapper.RolePermissionMapper;
import aliyun.cx.admin.mapper.UserRoleMapper;
import aliyun.cx.admin.service.RoleService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 角色管理服务实现类
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class RoleServiceImpl extends ServiceImpl<RoleMapper, Role> implements RoleService {

    private final UserRoleMapper userRoleMapper;
    private final RolePermissionMapper rolePermissionMapper;

    @Override
    public List<Role> getRolesByUserId(Long userId) {
        try {
            // 查询用户的角色ID列表
            QueryWrapper<UserRole> userRoleWrapper = new QueryWrapper<>();
            userRoleWrapper.eq("user_id", userId);
            List<UserRole> userRoles = userRoleMapper.selectList(userRoleWrapper);
            
            if (userRoles.isEmpty()) {
                return List.of();
            }
            
            // 获取角色ID列表
            List<Long> roleIds = userRoles.stream()
                .map(UserRole::getRoleId)
                .collect(Collectors.toList());
            
            // 查询角色详情
            return listByIds(roleIds);
        } catch (Exception e) {
            log.error("获取用户角色失败，用户ID: {}", userId, e);
            return List.of();
        }
    }

    @Override
    public Role getRoleByName(String roleName) {
        try {
            QueryWrapper<Role> wrapper = new QueryWrapper<>();
            wrapper.eq("name", roleName);
            return getOne(wrapper);
        } catch (Exception e) {
            log.error("根据角色名称获取角色失败，角色名称: {}", roleName, e);
            return null;
        }
    }

    @Override
    public boolean existsByName(String roleName) {
        try {
            QueryWrapper<Role> wrapper = new QueryWrapper<>();
            wrapper.eq("name", roleName);
            return count(wrapper) > 0;
        } catch (Exception e) {
            log.error("检查角色名称是否存在失败，角色名称: {}", roleName, e);
            return false;
        }
    }

    @Override
    public List<Role> getRolesByLevel(Integer level) {
        try {
            QueryWrapper<Role> wrapper = new QueryWrapper<>();
            wrapper.eq("level", level);
            wrapper.orderByAsc("level", "name");
            return list(wrapper);
        } catch (Exception e) {
            log.error("根据权限级别获取角色失败，级别: {}", level, e);
            return List.of();
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean assignPermissions(Long roleId, List<Long> permissionIds) {
        try {
            // 先删除现有的角色权限关联
            QueryWrapper<RolePermission> wrapper = new QueryWrapper<>();
            wrapper.eq("role_id", roleId);
            rolePermissionMapper.delete(wrapper);
            
            // 添加新的角色权限关联
            if (permissionIds != null && !permissionIds.isEmpty()) {
                List<RolePermission> rolePermissions = permissionIds.stream()
                    .map(permissionId -> {
                        RolePermission rp = new RolePermission();
                        rp.setRoleId(roleId);
                        rp.setPermissionId(permissionId);
                        return rp;
                    })
                    .collect(Collectors.toList());
                
                for (RolePermission rolePermission : rolePermissions) {
                    rolePermissionMapper.insert(rolePermission);
                }
            }
            
            log.info("为角色分配权限成功，角色ID: {}, 权限数量: {}", roleId, permissionIds != null ? permissionIds.size() : 0);
            return true;
        } catch (Exception e) {
            log.error("为角色分配权限失败，角色ID: {}", roleId, e);
            throw new RuntimeException("分配权限失败", e);
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean removePermissions(Long roleId, List<Long> permissionIds) {
        try {
            if (permissionIds == null || permissionIds.isEmpty()) {
                return true;
            }
            
            QueryWrapper<RolePermission> wrapper = new QueryWrapper<>();
            wrapper.eq("role_id", roleId);
            wrapper.in("permission_id", permissionIds);
            
            int deletedCount = rolePermissionMapper.delete(wrapper);
            log.info("移除角色权限成功，角色ID: {}, 移除数量: {}", roleId, deletedCount);
            return true;
        } catch (Exception e) {
            log.error("移除角色权限失败，角色ID: {}", roleId, e);
            throw new RuntimeException("移除权限失败", e);
        }
    }

    @Override
    public List<Long> getPermissionIdsByRoleId(Long roleId) {
        try {
            QueryWrapper<RolePermission> wrapper = new QueryWrapper<>();
            wrapper.eq("role_id", roleId);
            List<RolePermission> rolePermissions = rolePermissionMapper.selectList(wrapper);
            
            return rolePermissions.stream()
                .map(RolePermission::getPermissionId)
                .collect(Collectors.toList());
        } catch (Exception e) {
            log.error("获取角色权限ID失败，角色ID: {}", roleId, e);
            return List.of();
        }
    }
}